<script setup lang="ts">
import { useStatsStore } from '@/stores/stats'
import { onMounted, ref, onBeforeUnmount, watch } from 'vue'

const statsStore = useStatsStore()
const refreshInterval = ref<NodeJS.Timeout>()

const fetchData = () => {
  console.log('Fetching stats data...')
  statsStore.fetchStats()
}

onMounted(() => {
  fetchData()
  // 每30秒自动刷新数据
  refreshInterval.value = setInterval(fetchData, 30000)
})

// 清除定时器
onBeforeUnmount(() => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
  }
})

// 监听扫描完成事件
watch(() => statsStore.stats, (newStats) => {
  if (newStats) {
    console.log('Stats updated:', newStats)
  }
})
</script>

<template>
  <div class="stats-container">
    <div v-if="statsStore.loading" class="text-center py-4">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">Loading...</span>
      </div>
    </div>

    <div v-else-if="statsStore.error" class="alert alert-danger">
      {{ statsStore.error }}
      <button class="btn btn-sm btn-outline-danger ms-2" @click="fetchData">
        Retry
      </button>
    </div>

    <div v-else-if="statsStore.stats" class="d-flex flex-wrap justify-content-between align-items-center mb-3 gap-2">
      <div class="d-flex flex-wrap gap-2">
        <div class="badge bg-primary p-2">
          <span class="me-1">Total</span>
          <span>{{ statsStore.stats.total }}</span>
        </div>
        <div class="badge bg-success p-2">
          <span class="me-1">Connected</span>
          <span>{{ statsStore.stats.connected }}</span>
        </div>
        <div class="badge bg-danger p-2">
          <span class="me-1">Port Closed</span>
          <span>{{ statsStore.stats.port_closed }}</span>
        </div>
        <div class="badge bg-warning p-2">
          <span class="me-1">Failed</span>
          <span>{{ statsStore.stats.connection_failed }}</span>
        </div>
        <div class="badge bg-info p-2">
          <span class="me-1">Root</span>
          <span>{{ statsStore.stats.root_privilege }}</span>
        </div>
        <div class="badge bg-secondary p-2">
          <span class="me-1">Port Open</span>
          <span>{{ statsStore.stats.port_open }}</span>
        </div>
        <div class="badge bg-secondary p-2">
          <span class="me-1">Auth Success</span>
          <span>{{ statsStore.stats.auth_success }}</span>
        </div>
        <div class="badge bg-secondary p-2">
          <span class="me-1">Sudo Support</span>
          <span>{{ statsStore.stats.sudo_support }}</span>
        </div>
        <div class="badge bg-secondary p-2">
          <span class="me-1">Success Rate</span>
          <span>{{ statsStore.stats.success_rate }}</span>
        </div>
      </div>
      <button class="btn btn-primary ms-auto">
        <i class="bi bi-download me-1"></i> Export
      </button>
    </div>
  </div>
</template>
